package primary.primary0;

import java.util.ArrayList;
import java.util.List;

public class S0052N皇后II {

    /**
     * 21，直接抄S0051皇后的
     * 官方答案也并没有区别，没有因为这是求解法数量而不是求所有解法case而去换一种方法
     */
    class Solution {
        public int totalNQueens(int n) {
            if(n == 0){
                return 0;
            }
            boolean[] record1 = new boolean[n];
            boolean[] record2 = new boolean[n];
            boolean[] record3 = new boolean[2*n - 1];
            boolean[] record4 = new boolean[2*n - 1];

            nQueenHelp(n, n, 0, 0, record1, record2, record3, record4, new ArrayList<>());

            return res;
        }
        private int res = 0;

        private void nQueenHelp(int numsLeft, int n, int i, int j, boolean[] record1, boolean[] record2, boolean[] record3, boolean[] record4, List<int[]> curPath){
            if(numsLeft == 0 || record1[i] || record2[j] || record3[i + j] || record4[n - 1 + i - j]){
                // 找下一个遍历的点
                int[] nextPosi = nextPosi(n, i, j);
                if(nextPosi != null){
                    nQueenHelp(numsLeft, n, nextPosi[0], nextPosi[1], record1, record2, record3, record4, curPath);;
                }
                return;
            }
            // 其实这里可以有很多剪枝操作
            if((i >= 1 && !record1[i - 1])){
                return;
            }

            numsLeft = numsLeft - 1;
            record1[i] = true;
            record2[j] = true;
            record3[i + j] = true;
            record4[n - 1 + i - j] = true;
            curPath.add(new int[]{i, j});

            if(numsLeft == 0){
                res++;
            }else{
                int[] nextPosi = nextPosi(n, i, j);
                if(nextPosi != null){
                    nQueenHelp(numsLeft, n, nextPosi[0], nextPosi[1], record1, record2, record3, record4, curPath);
                }

            }

            numsLeft = numsLeft + 1;
            record1[i] = false;
            record2[j] = false;
            record3[i + j] = false;
            record4[n - 1 + i - j] = false;
            curPath.remove(curPath.size() - 1);

            int[] nextPosi = nextPosi(n, i, j);
            if(nextPosi != null){
                nQueenHelp(numsLeft, n, nextPosi[0], nextPosi[1], record1, record2, record3, record4, curPath);
            }

        }


        private int[] nextPosi(int n, int i, int j){
            if(j < n - 1){
                return new int[]{i, j + 1};
            }else{
                if(i < n - 1){
                    return new int[]{i + 1, 0};
                }else{
                    return null;
                }
            }
        }
    }
}
